#include <fcntl.h>
#include <signal.h>
#include <termios.h>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>

#include "SerialConnection.h"
#include <SiemensMC45.h>
#include <GPS_GSM_Tracker.h>
#include <system.h>

bool run;
pthread_mutex_t mutex;

SerialConnection gsmConnection(&mutex);
SerialConnection gpsConnection(&mutex);

SiemensMC45 gsm(&gsmConnection,&gsmConnection);
NMEA_GPS gps(&gpsConnection);

void terminate(int func) {
	run = false;
	printf("Got signal to terminate\n");
	gsmConnection.stop();
	gpsConnection.stop();
	usleep(1000000L);
}

void sleep(int millis) {
	usleep(millis * 1000);
}

uint32_t getSystemTimeMillis() {
	return time(NULL) * 1000UL;
}

void updateStatusIndicators() {}

void setLED(bool led) {}
void toggleLED() {}

void debugString(char* string) {
	printf("%s",string);
}

void initialize() {
	run = true;

	gsmConnection.init((char*)"/dev/ttyUSB0", B19200);
	gpsConnection.init((char*)"/dev/ttyUSB1", B38400);

	signal(SIGABRT, terminate);
	signal(SIGINT, terminate);
	signal(SIGTERM, terminate);
	pthread_mutex_init(&mutex, 0);

	gsmConnection.start();
	gpsConnection.start();
}

void someSillyTests() {
	//pthread_mutex_lock(&mutex);
	PhonebookEntry entry;
	char* name = (char*) "sunrise infoline";
	bool found = gsm.getPhonebookNumber(name, &entry);
	if (found) {
		fprintf(stderr, "Found the number %s\n", entry.number);
	} else {
		fprintf(stderr, "Did not find a number\n");
	}
	usleep(100000);

	ExtendedCellData eci;
	found = gsm.getExtendedCellData(eci);
	char someString[100];

	if (found) {
		fprintf(stderr,
				"Found the Area %d and cell ID %d. RSSI is %d/64(%d dBm)\n",
				eci.LAC, eci.cellId, eci.RSSI, eci.dBm);
		fprintf(stderr, "MCC:%d,MNC:%d,LAC:%d,CellID:%d\n", eci.MCC, eci.MNC,
				eci.LAC, eci.cellId);
		sprintf(someString, "MCC:%d,MNC:%d,LAC:%d,CellID:%d\n", eci.MCC,
				eci.MNC, eci.LAC, eci.cellId);
	}
	usleep(100000);

	SMS sms;
	if (!gsm.newReceivedSMS(sms)) {
		printf("No SMS received.\n");
	} else {
		printf("Got this SMS: \"%s\" from \"%s\"\n", sms.text, sms.number);
	}
}

int main() {
	initialize();
	mainLoop();
	terminate(0);
}
